package com.jeeplus.modules.api;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.config.properties.JeePlusProperites;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.agent.entity.Agent;
import com.jeeplus.modules.agent.service.AgentService;
import com.jeeplus.modules.api.common.ReqJson;
import com.jeeplus.modules.api.common.UUIDUtils;
import com.jeeplus.modules.api.enums.CostTypeEnum;
import com.jeeplus.modules.api.model.PurchaseModel;
import com.jeeplus.modules.api.model.SourceDTO;
import com.jeeplus.modules.api.utils.*;
import com.jeeplus.modules.api.wxpay.WxPayUtils;
import com.jeeplus.modules.banner.entity.Banner;
import com.jeeplus.modules.banner.service.BannerService;
import com.jeeplus.modules.brand.entity.Brand;
import com.jeeplus.modules.brand.service.BrandService;
import com.jeeplus.modules.cost.entity.Cost;
import com.jeeplus.modules.cost.service.CostService;
import com.jeeplus.modules.customerservice.entity.CustomerService;
import com.jeeplus.modules.customerservice.service.CustomerServiceService;
import com.jeeplus.modules.exhibitionhall.entity.ExhibitionHall;
import com.jeeplus.modules.exhibitionhall.service.ExhibitionHallService;
import com.jeeplus.modules.exhibitionhallmerchant.entity.ExhibitionHallMerchant;
import com.jeeplus.modules.exhibitionhallmerchant.service.ExhibitionHallMerchantService;
import com.jeeplus.modules.free.entity.Free;
import com.jeeplus.modules.free.service.FreeService;
import com.jeeplus.modules.hotintroduce.entity.HotIntroduce;
import com.jeeplus.modules.hotintroduce.service.HotIntroduceService;
import com.jeeplus.modules.image.entity.Image;
import com.jeeplus.modules.image.service.ImageService;
import com.jeeplus.modules.indexintro.entity.IndexIntro;
import com.jeeplus.modules.indexintro.service.IndexIntroService;
import com.jeeplus.modules.introduce.entity.Introduce;
import com.jeeplus.modules.introduce.service.IntroduceService;
import com.jeeplus.modules.market.entity.Market;
import com.jeeplus.modules.market.service.MarketService;
import com.jeeplus.modules.marketmerchant.entity.MarketMerchant;
import com.jeeplus.modules.marketmerchant.service.MarketMerchantService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.photo.entity.Photo;
import com.jeeplus.modules.photo.service.PhotoService;
import com.jeeplus.modules.purchase.entity.Purchase;
import com.jeeplus.modules.purchase.service.PurchaseService;
import com.jeeplus.modules.purchasecollect.entity.PurchaseCollect;
import com.jeeplus.modules.purchasecollect.service.PurchaseCollectService;
import com.jeeplus.modules.purchaserecord.entity.PurchaseRecord;
import com.jeeplus.modules.purchaserecord.service.PurchaseRecordService;
import com.jeeplus.modules.purchaseremark.entity.PurchaseRemark;
import com.jeeplus.modules.purchaseremark.service.PurchaseRemarkService;
import com.jeeplus.modules.source.entity.Source;
import com.jeeplus.modules.source.service.SourceService;
import com.jeeplus.modules.sourcecollect.entity.SourceCollect;
import com.jeeplus.modules.sourcecollect.service.SourceCollectService;
import com.jeeplus.modules.sourcerecord.entity.SourceRecord;
import com.jeeplus.modules.sourcerecord.service.SourceRecordService;
import com.jeeplus.modules.sys.service.AreaService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/user/")
@Slf4j
@CrossOrigin(origins = "*")
@SuppressWarnings("all")
public class MpController extends BaseController {

    private final Gson gson = new GsonBuilder().disableHtmlEscaping().create();


    @Value("${mp.app_id}")
    protected String appId;

    @Value("${mp.app_secret}")
    protected String appSecret;

    @Value("${wx.notify_url}")
    protected String notifyUrl;

    @Value("${mch.mch_no}")
    protected String mchNo;

    @Value("${mch.mch_secret}")
    protected String mchSecret;

    @Value("${mch.cert_path}")
    protected String certPath;

    @Value("${template.source}")
    protected String sourceNotify;

    @Value("${template.purchase}")
    protected String purchaseNotify;

    @Value("${mp.source_uri}")
    protected String sourceUri;

    @Value("${mp.purchase_uri}")
    protected String purchaseUri;

    private final BannerService bannerService;
    private final MemberService memberService;
    private final IntroduceService introduceService;
    private final JwtUtils jwtUtils;
    private final PhotoService photoService;
    private final FreeService freeService;
    private final IndexIntroService indexIntroService;
    private final CustomerServiceService customerServiceService;
    private final PurchaseService purchaseService;
    private final SourceService sourceService;
    private final PurchaseRemarkService purchaseRemarkService;
    private final BrandService brandService;
    private final SourceRecordService sourceRecordService;
    private final PurchaseRecordService purchaseRecordService;
    private final SourceCollectService sourceCollectService;
    private final PurchaseCollectService purchaseCollectService;
    private final ExhibitionHallMerchantService exhibitionHallMerchantService;
    private final MarketService marketService;
    private final ExhibitionHallService exhibitionHallService;
    private final MarketMerchantService marketMerchantService;
    private final AgentService agentService;
    private final HotIntroduceService hotIntroduceService;
    private final AreaService areaService;
    private final ImageService imageService;
    private final MessageUtils messageUtils;
    private final CostService costService;

    public MpController(BannerService bannerService, MemberService memberService, IntroduceService introduceService, JwtUtils jwtUtils, PhotoService photoService, FreeService freeService, IndexIntroService indexIntroService, CustomerServiceService customerServiceService, PurchaseService purchaseService, SourceService sourceService, PurchaseRemarkService purchaseRemarkService, BrandService brandService, SourceRecordService sourceRecordService, PurchaseRecordService purchaseRecordService, SourceCollectService sourceCollectService, PurchaseCollectService purchaseCollectService, ExhibitionHallMerchantService exhibitionHallMerchantService, MarketService marketService, ExhibitionHallService exhibitionHallService, MarketMerchantService marketMerchantService, AgentService agentService, HotIntroduceService hotIntroduceService, AreaService areaService, ImageService imageService, MessageUtils messageUtils, CostService costService) {
        this.bannerService = bannerService;
        this.memberService = memberService;
        this.introduceService = introduceService;
        this.jwtUtils = jwtUtils;
        this.photoService = photoService;
        this.freeService = freeService;
        this.indexIntroService = indexIntroService;
        this.customerServiceService = customerServiceService;
        this.purchaseService = purchaseService;
        this.sourceService = sourceService;
        this.purchaseRemarkService = purchaseRemarkService;
        this.brandService = brandService;
        this.sourceRecordService = sourceRecordService;
        this.purchaseRecordService = purchaseRecordService;
        this.sourceCollectService = sourceCollectService;
        this.purchaseCollectService = purchaseCollectService;
        this.exhibitionHallMerchantService = exhibitionHallMerchantService;
        this.marketService = marketService;
        this.exhibitionHallService = exhibitionHallService;
        this.marketMerchantService = marketMerchantService;
        this.agentService = agentService;
        this.hotIntroduceService = hotIntroduceService;
        this.areaService = areaService;
        this.imageService = imageService;
        this.messageUtils = messageUtils;
        this.costService = costService;
    }


    /**
     * 上传单张图片返回链接
     *
     * @return ajaxJson
     */
    @PostMapping("uploadFile")
    public AjaxJson addImages(@RequestParam(value = "file", required = false) MultipartFile[] file) {
        AjaxJson res = new AjaxJson();
        res.setMsg("上传失败");
        try {
            List<String> list = new ArrayList<>();
            if (file != null && file.length > 0) {
                for (MultipartFile multipartFile : file) {
                    String realPath = JeePlusProperites.newInstance().getUserfilesBaseDir() + "userfiles/1/files/authimage";
                    // String dateDir = DateTimeUtil.dateConvtoFmt(new Date(),
                    // "yyyyMM"); // 按日期存放上传的文件
                    String[] split = DateUtils.formatDate(new Date(), "yyyy-MM").split("-");
                    String dateDir = split[0] + "/" + split[1];
                    File path = new File(realPath + File.separator + dateDir);
                    if (!path.exists()) {
                        path.mkdirs();
                    }
                    String filename1 = multipartFile.getOriginalFilename();
                    String ext1 = null;
                    if (filename1 != null) {
                        ext1 = filename1.substring(filename1.lastIndexOf(".")).toLowerCase();
                    }
                    String fileName1 = DateUtils.formatDate(new Date(), "yyyyMMddHHmmss")
                            + RandomStringUtils.randomNumeric(4) + ext1;
                    File localFile1 = new File(path.getAbsolutePath() + File.separator + fileName1);
                    multipartFile.transferTo(localFile1);
                    list.add(filePath + "/userfiles/1/files/authimage/" + dateDir + "/" + fileName1);
                }
            }
            res.put("dataList", list);
            res.setCode(0);
            res.setMsg("提交成功");
        } catch (Exception e) {
            log.error("请求失败:{}", e);
        }
        return res;
    }


    /**
     * 获取code连接
     *
     * @return 连接
     */
    @RequestMapping("code")
    @ResponseBody
    public AjaxJson getCode() {
        AjaxJson ajaxJson = new AjaxJson();
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + mpAppId +
                "&redirect_uri=" + mpUri + "&response_type=code&scope=snsapi_userinfo" +
                "&state=STATE&connect_redirect=1#wechat_redirect";
        ajaxJson.put("data", url);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }


    /**
     * 获取openid
     *
     * @param code code
     * @return openid
     */
    @RequestMapping("login")
    public AjaxJson login(String code) {
        AjaxJson ajaxJson = new AjaxJson();
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + mpAppId + "&secret=" + mpAppSecret + "&code=" + code + "&grant_type=authorization_code";
        RestTemplate restTemplate = new RestTemplate();
        String template = restTemplate.getForObject(url, String.class);
        if (StringUtils.isNotBlank(template) && template.contains("errcode")) {
            ajaxJson.setMsg("登录失败");
            return ajaxJson;
        }
        String openId = JSONObject.fromObject(template).getString("openid");
        String accessToken = JSONObject.fromObject(template).getString("access_token");
        // 判断该用户是否存在
        Member member = memberService.findUniqueByProperty("openid", openId);
        Map<String, Object> map = new HashMap<>();
        if (Objects.nonNull(member)) {
            // 生成token
            map.put("id", member.getId());
            map.put("openid", member.getOpenid());
            map.put("type", member.getType());
            Map<String, Object> map1 = jwtUtils.generateToken(map);
            map1.put("id", member.getId());
            map1.put("photo", getRealPath(member.getPhoto()));
            map1.put("nickname", member.getNickname());
            map1.put("type", member.getType());
            map1.put("surplusDays", Objects.isNull(member.getEndDate()) ? 0 : DateUtils.getDistanceOfTwoDate(new Date(), member.getEndDate()));
            ajaxJson.put("data", map1);
            ajaxJson.setCode(0);
            ajaxJson.setMsg("登录成功");
        } else {
            // 获取用户信息
            String userUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" + openId + "&lang=zh_CN";
            String userTemplate = restTemplate.getForObject(userUrl, String.class);
            System.out.println(userTemplate);
            Member member1 = new Member();
            if (StringUtils.isNotBlank(userTemplate) && userTemplate.contains("errcode")) {
                // 获取默认头像
                Photo photo = photoService.get("1");
                member1.setNickname("老斯儿" + UUIDUtils.uuid(6));
                member1.setPhoto(getRealPath(photo.getPhoto()));
            } else {
                String nickname = JSONObject.fromObject(userTemplate).getString("nickname");
                String headimgurl = JSONObject.fromObject(userTemplate).getString("headimgurl");
                member1.setNickname(nickname);
                member1.setPhoto(headimgurl);
            }
            // 免费会员信息添加
//            Free free = freeService.get("1");
//            member1.setStartDate(new Date());
//            member1.setEndDate(addDate(free.getDays()));
            member1.setTakeState("0");
            member1.setType("1");
            member1.setOpenid(openId);
            member1.setPurchaseCount(0);
            member1.setCarCount(0);
            memberService.save(member1);
            map.put("id", member1.getId());
            map.put("openid", member1.getOpenid());
            map.put("type", member1.getType());
            Map<String, Object> map1 = jwtUtils.generateToken(map);
            map1.put("id", member1.getId());
            map1.put("photo", getRealPath(member1.getPhoto()));
            map1.put("nickname", member1.getNickname());
            map1.put("type", member1.getType());
            map1.put("surplusDays", Objects.isNull(member1.getEndDate()) ? 0 : DateUtils.getDistanceOfTwoDate(new Date(), member1.getEndDate()));
            ajaxJson.put("data", map1);
            ajaxJson.setCode(0);
            ajaxJson.setMsg("授权成功");
        }
        return ajaxJson;
    }


    /**
     * 首页轮播图
     *
     * @return 数据
     */
    @RequestMapping("/banner")
    public AjaxJson banner() {
        AjaxJson ajaxJson = new AjaxJson();
        List<Banner> list = bannerService.findList(new Banner());
        List<String> imgList = new CopyOnWriteArrayList<>();
        list.forEach(banner -> imgList.add(getRealPath(banner.getImg())));
        ajaxJson.put("data", imgList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }


    /**
     * 简介
     *
     * @return 数据
     */
    @RequestMapping("/intro")
    public AjaxJson intro() {
        AjaxJson ajaxJson = new AjaxJson();
        Introduce introduce = introduceService.get("1");
        Map<String, Object> map = new HashMap<>();
        map.put("title", introduce.getTitle());
        map.put("intro", introduce.getContent());
        map.put("video", getRealPath(introduce.getVideo()));
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }


    /**
     * 热门服务顶部图片与简介
     *
     * @return 数据
     */
    @RequestMapping("/hotServiceTop")
    public AjaxJson hotServiceTop() {
        AjaxJson ajaxJson = new AjaxJson();
        HotIntroduce hotIntroduce = hotIntroduceService.get("1");
        Map<String, Object> map = new HashMap<>();
        map.put("intro", hotIntroduce.getIntro());
        map.put("img", getRealPath(hotIntroduce.getImg()));
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }


    /**
     * 首页功能简介
     *
     * @return 数据
     */
    @RequestMapping("/indexIntro")
    public AjaxJson indexIntro() {
        AjaxJson ajaxJson = new AjaxJson();
        List<IndexIntro> list = indexIntroService.findList(new IndexIntro());
        for (IndexIntro indexIntro : list) {
            if (indexIntro.getId().equals("1")) {
                ajaxJson.put("data1", indexIntro.getIntro());
            } else if (indexIntro.getId().equals("2")) {
                ajaxJson.put("data2", indexIntro.getIntro());
            } else if (indexIntro.getId().equals("3")) {
                ajaxJson.put("data3", indexIntro.getIntro());
            }
        }
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 创建热门服务
     *
     * @return 数据
     */
    @RequestMapping("/createCusService")
    public AjaxJson createCusService(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String name = req.getString("name");
        String mobile = req.getString("mobile");
        String wechat = req.getString("wechat");
        String serviceContent = req.getString("serviceContent");
        String brand = req.getString("brand");
        String motorcycleType = req.getString("motorcycleType");
        String budget = req.getString("budget");
        String registrationCity = req.getString("registrationCity");
        String remark = req.getString("remark");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        CustomerService customerService = new CustomerService();
        customerService.setU(member);
        customerService.setName(name);
        customerService.setMobile(mobile);
        customerService.setServiceContent(serviceContent);
        customerService.setBrand(brand);
        customerService.setMotorcycleType(motorcycleType);
        customerService.setBudget(budget);
        customerService.setRegistrationCity(registrationCity);
        customerService.setRemark(remark);
        customerService.setWechat(wechat);
        customerServiceService.save(customerService);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("操作成功");
        return ajaxJson;
    }

    /**
     * 发布求购
     *
     * @return 数据
     */
//    // @TokenValidate
    @RequestMapping("/pushPurchase")
    public AjaxJson pushPurchase(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String id = req.getString("id");
        String callName = req.getString("callName");
        String brand = req.getString("brand");
        String motorcycleType = req.getString("motorcycleType");
        String carStyle = req.getString("carStyle");
        String colour = req.getString("colour");
        String shiftType = req.getString("shiftType");
        String registeredDate = req.getString("registeredDate");
        String mileage = req.getString("mileage");
        String age = req.getString("age");
        String carBudget = req.getString("carBudget");
        String mobile = req.getString("mobile");
        String pushState = req.getString("pushState");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderId = sf.format(System.currentTimeMillis()) + orderUuid();

        Purchase purchase = new Purchase();
        purchase.setId(id);
        if (StringUtils.isBlank(id)) {
            purchase.setIsNewRecord(true);
            purchase.setId(orderId);
        }
        purchase.setU(member);
        purchase.setUserType(member.getVipType());
        purchase.setCallName(callName);
        purchase.setBrand(brand);
        purchase.setMotorcycleType(motorcycleType);
        purchase.setCarStyle(carStyle);
        purchase.setColour(colour);
        purchase.setShiftType(shiftType);
        purchase.setRegisteredDate(registeredDate);
        purchase.setMileage(mileage);
        purchase.setAge(age);
        purchase.setCarBudget(carBudget);
        purchase.setMobile(mobile);
        purchase.setPushState(pushState);

        // 金额处理
        // 查询发布车源支付金额
        Cost cost = new Cost();
        cost.setBusinessType(CostTypeEnum.PURCHASE.getCode().toString());
        List<Cost> list1 = costService.findList(cost);
        if (CollUtil.isNotEmpty(list1)) {
            Cost cost1 = list1.get(0);
            // 如果金额大于0走支付
            if (new BigDecimal(cost1.getAmount()).compareTo(BigDecimal.ZERO) > 0) {
                LinkedHashMap<String, Object> stringObjectLinkedHashMap = WxPayUtils.wxPay(member.getOpenid(), "发布车源", orderId + orderUuid(), cost1.getAmount(), "1", appId, mchNo, notifyUrl, mchSecret);
            }
        }
        purchaseService.saveAndSendMsg(purchase, sourceNotify, sourceUri);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("发布成功");
        return ajaxJson;
    }

    /**
     * 求购发布注意事项
     *
     * @return 数据
     */
    @RequestMapping("/purchaseRemark")
    public AjaxJson purchaseRemark() {
        AjaxJson ajaxJson = new AjaxJson();
        PurchaseRemark purchaseRemark = purchaseRemarkService.get("1");
        ajaxJson.put("data", purchaseRemark.getIntro());
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    private synchronized String orderUuid() {
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            int r = random.nextInt(10); //每次随机出一个数字（0-9）
            code.append(r);  //把每次随机出的数字拼在一起
        }
        return code.toString();
    }


    /**
     * 发布车源
     *
     * @return 数据
     */
//    // @TokenValidate
    @RequestMapping("/pushSource")
    public AjaxJson pushSource(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String id = req.getString("id");
        String carImg = req.getString("carImg");
        String identificationPhoto = req.getString("identificationPhoto");
        String vin = req.getString("vin");
        String brand = req.getString("brand");
        String motorclcleType = req.getString("motorcycleType");
        String carStyle = req.getString("carStyle");
        String registrationDate = req.getString("registrationDate");
        String outDate = req.getString("outDate");
        String mileage = req.getString("mileage");
        String colour = req.getString("colour");
        String shiftType = req.getString("shiftType");
        Integer transferNum = req.getInteger("transferNum");
        String njDate = req.getString("njDate");
        String jqDate = req.getString("jqDate");
        String emissionStandard = req.getString("emissionStandard");
        String pfPrice = req.getString("pfPrice");
        String lsPrice = req.getString("lsPrice");
        String mobile = req.getString("mobile");
        String carRemark = req.getString("carRemark");
        String conditionRemark = req.getString("conditionRemark");
        String flawImg = req.getString("flawImg");
        String pushState = req.getString("pushState");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        String orderId = sf.format(System.currentTimeMillis()) + orderUuid();
        Source source = new Source();
        source.setId(id);
        if (StringUtils.isBlank(id)) {
            source.setIsNewRecord(true);
            source.setId(orderId);
        }
        source.setU(member);
        source.setUserType(member.getVipType());
        source.setCarImg(carImg);
        source.setIdentificationPhoto(identificationPhoto);
        source.setVin(vin);
        source.setBrand(brand);
        source.setMotorclcleType(motorclcleType);
        source.setCarStyle(carStyle);
        source.setRegistrationDate(registrationDate);
        source.setOutDate(outDate);
        source.setMileage(mileage);
        source.setColour(colour);
        source.setShiftType(shiftType);
        source.setTransferNum(transferNum);
        source.setNjDate(njDate);
        source.setJqDate(jqDate);
        source.setEmissionStandard(emissionStandard);
        source.setPfPrice(pfPrice);
        source.setLsPrice(lsPrice);
        source.setMobile(mobile);
        source.setCarRemark(carRemark);
        source.setConditionRemark(conditionRemark);
        source.setFlawImg(flawImg);
        source.setPushState(pushState);
        source.setIsUp("0"); // 支付成功修改上架状态
        source.setIsSell("0");
        source.setIcon(StringUtils.isBlank(carImg) ? "" : carImg.split(",")[0]);
        //调取微信支付
        if (StringUtils.isBlank(member.getOpenid())) {
            return ajaxJson.error("请登录后发布");
        }
        // 用户过期调用支付
        // 检验该用户是否会员过期
        Boolean aBoolean = checkOutDate(member.getEndDate());
        if (!aBoolean) {
            // 查询发布车源支付金额
            Cost cost = new Cost();
            cost.setBusinessType(CostTypeEnum.SOURCE.getCode().toString());
            List<Cost> list = costService.findList(cost);
            if (CollUtil.isEmpty(list)) {
                return ajaxJson.error("发布失败，请联系管理员");
            }
            Cost cost1 = list.get(0);
            // 如果金额大于0走支付
            if (new BigDecimal(cost1.getAmount()).compareTo(BigDecimal.ZERO) > 0) {
                LinkedHashMap<String, Object> stringObjectLinkedHashMap = WxPayUtils.wxPay(member.getOpenid(), "发布车源", orderId + orderUuid(), cost1.getAmount(), "1", appId, mchNo, notifyUrl, mchSecret);
            }
        }
        Purchase purchase = new Purchase();
        purchase.setBrand(source.getBrand());
        purchase.setMotorcycleType(source.getMotorclcleType());
        purchase.setCarStyle(source.getCarStyle());
        purchase.setColour(source.getColour());
        purchase.setShiftType(source.getShiftType());
        purchase.setRegisteredDate(source.getRegistrationDate());
        purchase.setMileage(source.getMileage());
        // 计算零售价
        BigDecimal bigDecimal = new BigDecimal(source.getLsPrice()).setScale(1, RoundingMode.HALF_UP);
        purchase.setDataScope("  AND (a.car_budget BETWEEN '" + bigDecimal + "' AND '" + (bigDecimal.add(new BigDecimal("1.00"))).setScale(1, RoundingMode.HALF_UP) + "')");
        List<Purchase> list = purchaseService.findList(purchase);
        if (CollUtil.isNotEmpty(list)) {
            list.sort(Comparator.comparing(Purchase::getCarBudget));
            // 找到发布车源的用户
            List<String> collect = list.stream().map(o -> o.getU().getId()).collect(Collectors.toList());
            String collect1 = collect.stream().collect(Collectors.joining(","));
            Member member1 = new Member();
            member1.setDataScope(" AND a.id in ('" + collect1 + "')");
            List<Member> list1 = memberService.findList(member1);
            List<String> collect2 = list1.stream().map(Member::getOpenid).collect(Collectors.toList());
            collect2.forEach(o -> {
                messageUtils.newSourceNotify(o, purchaseNotify, purchaseUri, purchase);
            });
        }
        sourceService.save(source);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    // 检验用户的免费时间
    private Boolean checkOutDate(Date endDate) {
        Boolean date = true;
        if (endDate.compareTo(new Date()) < 0) {
            date = false;
        }
        return date;
    }

    /**
     * 车源列表
     *
     * @return 数据
     */
    @RequestMapping("/sourceList")
    public AjaxJson sourceList(SourceDTO sourceDTO) {
        AjaxJson ajaxJson = new AjaxJson();
        Source source = new Source();
        Page<Source> page = new Page<>();
        if (StringUtils.isNotBlank(sourceDTO.getIdList())) {
            String[] split = sourceDTO.getIdList().split(",");
            source.setDataScope(" AND a.id in ('" + sourceDTO.getIdList() + "')");
            page.setPageNo(1);
            page.setPageSize(split.length);
        } else {
            source.setBrand(sourceDTO.getBrand());
            source.setAddress(sourceDTO.getAddr());
            source.setPushState("2");
            source.setMotorclcleType(sourceDTO.getMotorclcleType());
            source.setRegistrationDate(sourceDTO.getRegistrationDate());
            source.setMileage(sourceDTO.getMileage());
            source.setUserType(sourceDTO.getUserType());
            source.setDisplacement(sourceDTO.getDisplacement());
            source.setLsPrice(sourceDTO.getPrice());
            source.setColour(sourceDTO.getColour());
            if (Objects.isNull(sourceDTO.getPageNo()) || Objects.isNull(sourceDTO.getPageSize())) {
                return ajaxJson.error("分页参数不能为空");
            }
            if (StringUtils.isBlank(sourceDTO.getDefalutSort()) || sourceDTO.getDefalutSort().equals("1")) {
                page.setOrderBy(" a.create_date desc");
            } else if (sourceDTO.getDefalutSort().equals("2")) {
                page.setOrderBy(" a.create_date asc");
            }
            if (StringUtils.isNotBlank(sourceDTO.getPriceSort())) {
                if (sourceDTO.getPriceSort().equals("1")) {
                    page.setOrderBy(" a.ls_price desc");
                } else if (sourceDTO.getPriceSort().equals("2")) {
                    page.setOrderBy(" a.ls_price asc");
                }
            }
        }
        // 公众号详情推送显示
        page.setPageNo(sourceDTO.getPageNo());
        page.setPageSize(sourceDTO.getPageSize());
        Page<Source> page1 = sourceService.findPage(page, source);
        ajaxJson.put("total", page1.getLast());
        ajaxJson.put("count", page1.getCount());
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        for (Source source1 : page1.getList()) {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("id", StringUtils.isBlank(source1.getId()) ? "" : source1.getId());
            map.put("icon", StringUtils.isBlank(source1.getIcon()) ? "" : getRealPath(source1.getIcon()));
            map.put("brand", StringUtils.isBlank(source1.getBrand()) ? "" : source1.getBrand());
            map.put("motorclcleType", StringUtils.isBlank(source1.getMotorclcleType()) ? "" : source1.getMotorclcleType());
            map.put("carStyle", StringUtils.isBlank(source1.getCarStyle()) ? "" : source1.getCarStyle());
            map.put("registrationDate", StringUtils.isBlank(source1.getRegistrationDate()) ? "" : source1.getRegistrationDate());
            map.put("mileage", StringUtils.isBlank(source1.getMileage()) ? "" : source1.getMileage());
            map.put("pfPrice", StringUtils.isBlank(source1.getPfPrice()) ? "" : source1.getPfPrice());
            map.put("lsPrice", StringUtils.isBlank(source1.getLsPrice()) ? "" : source1.getLsPrice());
            map.put("colour", StringUtils.isBlank(source1.getColour()) ? "" : source1.getColour());
            mapList.add(map);
        }
        ajaxJson.put("data", mapList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 获取所有品牌
     *
     * @return 数据
     */
    @RequestMapping("/getBrand")
    public AjaxJson getBrand() {
        AjaxJson ajaxJson = new AjaxJson();
        Brand brand = new Brand();
        brand.setParent(new Brand("0"));
        List<Brand> list = brandService.findList(brand);
        list.sort(Comparator.comparing(Brand::getSort));
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        Map<String, List<Brand>> collect = list.stream().collect(Collectors.groupingBy(Brand::getLetter));
        List<String> strings = Arrays.asList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
        List<Map<String, Object>> mapList1 = new CopyOnWriteArrayList<>();
        strings.forEach(o -> {
            Map<String, Object> data1 = new ConcurrentHashMap<>();
            List<Map<String, Object>> mapList2 = new CopyOnWriteArrayList<>();
            List<Brand> brands = collect.get(o);
            if (CollectionUtil.isNotEmpty(brands)) {
                brands.forEach(p -> {
                    Map<String, Object> data2 = new ConcurrentHashMap<>();
                    data2.put("id", p.getId());
                    data2.put("icon", getRealPath(p.getIcon()));
                    data2.put("name", p.getBrand());
                    mapList2.add(data2);
                });
                data1.put("title", o);
                data1.put("data", mapList2);
                mapList1.add(data1);
            }
        });
        ajaxJson.put("data", mapList1);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 获取车型数据
     *
     * @return 数据
     */
    @RequestMapping("/getMotorcycleType")
    public AjaxJson getMotorcycleType(String brandId) {
        AjaxJson ajaxJson = new AjaxJson();
        Brand brand = new Brand();
        if (StringUtils.isBlank(brandId)) {
            return ajaxJson.error("品牌id不能为空");
        }
        brand.setParent(new Brand(brandId));
        List<Brand> list = brandService.findList(brand);
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        for (Brand brand1 : list) {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("id", brand1.getId());
            map.put("title", brand1.getMotorcycleType());
            mapList.add(map);
        }
        ajaxJson.put("data", mapList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 获取车款
     *
     * @return 数据
     */
    @RequestMapping("/getYearStyle")
    public AjaxJson getYearStyle(String cateId) {
        AjaxJson ajaxJson = new AjaxJson();
        Brand brand = new Brand();
        brand.setParent(new Brand(cateId));
        List<Brand> list = brandService.findList(brand);
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        list.sort(Comparator.comparing(Brand::getYearStyle));
        for (Brand brand1 : list) {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("id", brand1.getId());
            map.put("title", brand1.getCarStyle());
            mapList.add(map);
        }
        ajaxJson.put("data", mapList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 车源详情
     *
     * @return 数据
     */
//    // @TokenValidate
    @RequestMapping("/sourceInfo")
    public AjaxJson sourceInfo(String uid, String id) {
        AjaxJson ajaxJson = new AjaxJson();
        if (StringUtils.isBlank(id)) {
            ajaxJson.setMsg("车源id不能为空");
            return ajaxJson;
        }
        Source source = sourceService.get(id);
        if (Objects.isNull(source)) {
            ajaxJson.setMsg("该车源不存在");
            return ajaxJson;
        }
        // 判断用户是否收藏
        List<SourceCollect> list = new ArrayList<>();
        if (StringUtils.isNotBlank(uid)) {
            SourceCollect sourceCollect = new SourceCollect();
            sourceCollect.setU(new Member(uid));
            sourceCollect.setSource(source);
            list = sourceCollectService.findList(sourceCollect);
        }
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put("id", source.getId());
        map.put("carImg", StringUtils.isBlank(source.getCarImg()) ? new ArrayList<>() : convertImageList(source.getCarImg()));
        map.put("flawImg", StringUtils.isBlank(source.getFlawImg()) ? new ArrayList<>() : convertImageList(source.getFlawImg()));
        map.put("brand", StringUtils.isBlank(source.getBrand()) ? "" : source.getBrand());
        map.put("motorcycleType", StringUtils.isBlank(source.getMotorclcleType()) ? "" : source.getMotorclcleType());
        map.put("carStyle", StringUtils.isBlank(source.getCarStyle()) ? "" : source.getCarStyle());
        map.put("lsPrice", StringUtils.isBlank(source.getLsPrice()) ? "" : source.getLsPrice());
        map.put("pfPrice", StringUtils.isBlank(source.getPfPrice()) ? "" : source.getPfPrice());
        map.put("vin", StringUtils.isBlank(source.getVin()) ? "" : source.getVin());
        map.put("registrationDate", StringUtils.isBlank(source.getRegistrationDate()) ? "" : source.getRegistrationDate());
        map.put("outDate", StringUtils.isBlank(source.getOutDate()) ? "" : source.getOutDate());
        map.put("mileage", StringUtils.isBlank(source.getMileage()) ? "" : source.getMileage());
        map.put("colour", StringUtils.isBlank(source.getColour()) ? "" : source.getColour());
        map.put("shiftType", StringUtils.isBlank(source.getShiftType()) ? "" : source.getShiftType());
        map.put("transferNum", Objects.isNull(source.getTransferNum()) ? 0 : source.getTransferNum());
        map.put("njDate", StringUtils.isBlank(source.getNjDate()) ? "" : source.getNjDate());
        map.put("jqDate", StringUtils.isBlank(source.getJqDate()) ? "" : source.getJqDate());
        map.put("emissionStandard", StringUtils.isBlank(source.getEmissionStandard()) ? "" : source.getEmissionStandard());
        map.put("mobile", StringUtils.isBlank(source.getMobile()) ? "" : source.getMobile());
        map.put("conditionRemark", StringUtils.isBlank(source.getConditionRemark()) ? "" : source.getConditionRemark());
        map.put("isUp", StringUtils.isBlank(source.getIsUp()) ? "0" : source.getIsUp());
        map.put("isSell", StringUtils.isBlank(source.getIsSell()) ? "0" : source.getIsSell());
        map.put("isCollect", CollectionUtil.isEmpty(list) ? "0" : "1");
        // 添加车源浏览记录
        SourceRecord sourceRecord = new SourceRecord();
//        sourceRecord.setU();
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 添加车源浏览记录
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/addSourceRecord")
    public AjaxJson addSourceRecord(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String sourceId = req.getString("sourceId");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(sourceId)) {
            ajaxJson.setMsg("车源id不能为空");
            return ajaxJson;
        }
        Source source = sourceService.get(sourceId);
        if (Objects.isNull(source)) {
            ajaxJson.setMsg("该车源不存在");
            return ajaxJson;
        }
        SourceRecord sourceRecord = new SourceRecord();
        sourceRecord.setSource(source);
        sourceRecord.setU(member);
        sourceRecordService.save(sourceRecord);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("操作成功");
        return ajaxJson;
    }


    /**
     * 添加求购浏览记录
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/addPurchaseRecord")
    public AjaxJson addpurchaseRecord(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String purchaseId = req.getString("purchaseId");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(purchaseId)) {
            ajaxJson.setMsg("求购id不能为空");
            return ajaxJson;
        }
        Purchase purchase = purchaseService.get(purchaseId);
        if (Objects.isNull(purchase)) {
            ajaxJson.setMsg("该求购不存在");
            return ajaxJson;
        }
        PurchaseRecord purchaseRecord = new PurchaseRecord();
        purchaseRecord.setPurchase(purchase);
        purchaseRecord.setU(member);
        purchaseRecordService.save(purchaseRecord);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("操作成功");
        return ajaxJson;
    }

    /**
     * 我浏览的车源
     *
     * @return 数据
     */
    @RequestMapping("/userSourceRecord")
    public AjaxJson userSourceRecord(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        String uid = req.getString("uid");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (Objects.isNull(pageNo) || Objects.isNull(pageSize)) {
            ajaxJson.setMsg("分页参数不能为空");
            return ajaxJson;
        }
        SourceRecord sourceRecord = new SourceRecord();
        sourceRecord.setU(member);
        Page<SourceRecord> page = sourceRecordService.findPage(new Page<>(pageNo, pageSize), sourceRecord);
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        for (SourceRecord record : page.getList()) {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("id", record.getSource().getId());
            map.put("pfPrice", StringUtils.isBlank(record.getSource().getPfPrice()) ? "" : record.getSource().getPfPrice());
            map.put("lsPrice", StringUtils.isBlank(record.getSource().getLsPrice()) ? "" : record.getSource().getLsPrice());
            map.put("mileage", StringUtils.isBlank(record.getSource().getMileage()) ? "" : record.getSource().getMileage());
            map.put("icon", StringUtils.isBlank(record.getSource().getIcon()) ? "" : getRealPath(record.getSource().getIcon()));
            map.put("brand", StringUtils.isBlank(record.getSource().getBrand()) ? "" : record.getSource().getBrand());
            map.put("motorcycleType", StringUtils.isBlank(record.getSource().getMotorclcleType()) ? "" : record.getSource().getMotorclcleType());
            map.put("carStyle", StringUtils.isBlank(record.getSource().getCarStyle()) ? "" : record.getSource().getCarStyle());
            map.put("registrationDate", StringUtils.isBlank(record.getSource().getRegistrationDate()) ? "" : record.getSource().getRegistrationDate());
            map.put("colour", StringUtils.isBlank(record.getSource().getColour()) ? "" : record.getSource().getColour());
            mapList.add(map);
        }
        ajaxJson.put("total", page.getLast());
        ajaxJson.put("count", page.getCount());
        ajaxJson.put("data", mapList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 我浏览的求购
     *
     * @return 数据
     */
    @RequestMapping("/userPurchaseRecord")
    public AjaxJson userPurchaseRecord(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (Objects.isNull(pageNo) || Objects.isNull(pageSize)) {
            ajaxJson.setMsg("分页参数不能为空");
            return ajaxJson;
        }
        PurchaseRecord purchaseRecord = new PurchaseRecord();
        purchaseRecord.setU(member);
        Page<PurchaseRecord> page = purchaseRecordService.findPage(new Page<>(pageNo, pageSize), purchaseRecord);
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        for (PurchaseRecord record : page.getList()) {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("id", record.getPurchase().getId());
            map.put("brand", record.getPurchase().getBrand());
            map.put("motorcycleType", record.getPurchase().getMotorcycleType());
            map.put("carStyle", record.getPurchase().getCarStyle());
            map.put("registrationDate", record.getPurchase().getRegisteredDate());
            map.put("mobile", record.getPurchase().getMobile());
            mapList.add(map);
        }
        ajaxJson.put("total", page.getLast());
        ajaxJson.put("count", page.getCount());
        ajaxJson.put("data", mapList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 清空车源记录
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/deleteSourceRecord")
    public AjaxJson deleteSourceRecord(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        SourceRecord sourceRecord = new SourceRecord();
        sourceRecord.setU(member);
        List<SourceRecord> list = sourceRecordService.findList(sourceRecord);
        sourceRecordService.deleteAll(list);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("操作成功");
        return ajaxJson;
    }

    /**
     * 清空求购浏览记录
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/deletePurchaseRecord")
    public AjaxJson deletePurchaseRecord(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        PurchaseRecord purchaseRecord = new PurchaseRecord();
        purchaseRecord.setU(member);
        List<PurchaseRecord> list = purchaseRecordService.findList(purchaseRecord);
        purchaseRecordService.deleteAll(list);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("操作成功");
        return ajaxJson;
    }

    /**
     * 收藏车源
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/collectSource")
    public AjaxJson collectSource(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String sourceId = req.getString("sourceId");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(sourceId)) {
            ajaxJson.setMsg("车源id不能为空");
            return ajaxJson;
        }
        Source source = sourceService.get(sourceId);
        if (Objects.isNull(source)) {
            ajaxJson.setMsg("该车源不存在");
            return ajaxJson;
        }
        SourceCollect sourceCollect = new SourceCollect();
        sourceCollect.setSource(source);
        sourceCollect.setU(member);
        // 判断用户是否收藏车源
        List<SourceCollect> list = sourceCollectService.findList(sourceCollect);
        if (CollectionUtil.isNotEmpty(list)) {
            sourceCollectService.deleteAll(list);
            ajaxJson.setMsg("已取消收藏");
        } else {
            sourceCollectService.save(sourceCollect);
            ajaxJson.setMsg("收藏成功");
        }
        ajaxJson.setCode(0);
        return ajaxJson;
    }

    /**
     * 收藏求购
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/collectPurchase")
    public AjaxJson collectPurchase(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String purchaseId = req.getString("purchaseId");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(purchaseId)) {
            ajaxJson.setMsg("求购id不能为空");
            return ajaxJson;
        }
        Purchase purchase = purchaseService.get(purchaseId);
        if (Objects.isNull(purchase)) {
            ajaxJson.setMsg("该求购不存在");
            return ajaxJson;
        }
        PurchaseCollect purchaseCollect = new PurchaseCollect();
        purchaseCollect.setPurchase(purchase);
        purchaseCollect.setU(member);
        List<PurchaseCollect> list = purchaseCollectService.findList(purchaseCollect);
        if (CollectionUtil.isNotEmpty(list)) {
            ajaxJson.setMsg("已取消收藏");
            purchaseCollectService.deleteAll(list);
        } else {
            ajaxJson.setMsg("收藏成功");
            purchaseCollectService.save(purchaseCollect);
        }
        ajaxJson.setCode(0);
        return ajaxJson;
    }

    /**
     * 我收藏的车源
     *
     * @return 数据
     */
    @RequestMapping("/myCollectSource")
    public AjaxJson myCollectSource(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (Objects.isNull(pageNo) || Objects.isNull(pageSize)) {
            ajaxJson.setMsg("分页参数不能为空");
            return ajaxJson;
        }
        SourceCollect sourceCollect = new SourceCollect();
        sourceCollect.setU(member);
        Page<SourceCollect> page = sourceCollectService.findPage(new Page<>(pageNo, pageSize), sourceCollect);
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        for (SourceCollect collect : page.getList()) {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("id", collect.getSource().getId());
            map.put("pfPrice", StringUtils.isBlank(collect.getSource().getPfPrice()) ? "" : collect.getSource().getPfPrice());
            map.put("lsPrice", StringUtils.isBlank(collect.getSource().getLsPrice()) ? "" : collect.getSource().getLsPrice());
            map.put("mileage", StringUtils.isBlank(collect.getSource().getMileage()) ? "" : collect.getSource().getMileage());
            map.put("icon", StringUtils.isBlank(collect.getSource().getIcon()) ? "" : getRealPath(collect.getSource().getIcon()));
            map.put("brand", StringUtils.isBlank(collect.getSource().getBrand()) ? "" : collect.getSource().getBrand());
            map.put("motorcycleType", StringUtils.isBlank(collect.getSource().getMotorclcleType()) ? "" : collect.getSource().getMotorclcleType());
            map.put("carStyle", StringUtils.isBlank(collect.getSource().getCarStyle()) ? "" : collect.getSource().getCarStyle());
            map.put("registrationDate", StringUtils.isBlank(collect.getSource().getRegistrationDate()) ? "" : collect.getSource().getRegistrationDate());
            map.put("colour", StringUtils.isBlank(collect.getSource().getColour()) ? "" : collect.getSource().getColour());
            mapList.add(map);

        }
        ajaxJson.put("total", page.getLast());
        ajaxJson.put("count", page.getCount());
        ajaxJson.put("data", mapList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 我收藏的求购
     *
     * @return 数据
     */
    @RequestMapping("/myCollectPurchase")
    public AjaxJson myCollectPurchase(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (Objects.isNull(pageNo) || Objects.isNull(pageSize)) {
            ajaxJson.setMsg("分页参数不能为空");
            return ajaxJson;
        }
        PurchaseCollect purchaseCollect = new PurchaseCollect();
        purchaseCollect.setU(member);
        Page<PurchaseCollect> page = purchaseCollectService.findPage(new Page<>(pageNo, pageSize), purchaseCollect);
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        List<Purchase> collect1 = page.getList().stream().map(o -> o.getPurchase()).collect(Collectors.toList());
        for (Purchase o : collect1) {
            Map<String, Object> map = new ConcurrentHashMap<>();
//            map.put("isCollect", CollUtil.isNotEmpty(collectList) && collectList.contains(o.getId()) ? 1 : 0);
            map.put("callName", StringUtils.isBlank(o.getCallName()) ? "" : o.getCallName());
            map.put("brand", StringUtils.isBlank(o.getBrand()) ? "" : o.getBrand());
            map.put("carStyle", StringUtils.isBlank(o.getCarStyle()) ? "" : o.getCarStyle());
            map.put("motorcycleType", StringUtils.isBlank(o.getMotorcycleType()) ? "" : o.getMotorcycleType());
            map.put("colour", StringUtils.isBlank(o.getColour()) ? "" : o.getColour());
            map.put("shift_type", StringUtils.isBlank(o.getShiftType()) ? "" : o.getShiftType());
            map.put("registeredDate", StringUtils.isBlank(o.getRegisteredDate()) ? "" : o.getRegisteredDate());
            map.put("mileage", StringUtils.isBlank(o.getMileage()) ? "" : o.getMileage());
            map.put("age", StringUtils.isBlank(o.getAge()) ? "" : o.getAge());
            map.put("carBudget", StringUtils.isBlank(o.getCarBudget()) ? "" : o.getCarBudget());
            map.put("mobile", StringUtils.isBlank(o.getMobile()) ? "" : o.getMobile());
            map.put("id", StringUtils.isBlank(o.getId()) ? "" : o.getId());;
            mapList.add(map);
        }
        ajaxJson.put("total", page.getLast());
        ajaxJson.put("count", page.getCount());
        ajaxJson.put("data", mapList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 求购草稿
     *
     * @return 数据
     */
    @RequestMapping("/purchaseDraft")
    public AjaxJson purchaseDraft(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        Purchase purchase = new Purchase();
        purchase.setU(member);
        purchase.setPushState("1");
        List<Purchase> list = purchaseService.findList(purchase);
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        for (Purchase purchase1 : list) {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("id", purchase1.getId());
            map.put("colour", purchase1.getColour());
            map.put("callName", purchase1.getCallName());
            map.put("brand", purchase1.getBrand());
            map.put("motorcycleType", purchase1.getMotorcycleType());
            map.put("carStyle", purchase1.getCarStyle());
            map.put("registrationDate", purchase1.getRegisteredDate());
            map.put("shiftType", purchase1.getShiftType());
            map.put("mileage", purchase1.getMileage());
            map.put("age", purchase1.getAge());
            map.put("carBudget", purchase1.getCarBudget());
            map.put("mobile", purchase1.getMobile());
            mapList.add(map);
        }
        ajaxJson.put("data", mapList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 车源草稿
     *
     * @return 数据
     */
    @RequestMapping("/sourceDraft")
    public AjaxJson sourceDraft(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        Source source = new Source();
        source.setU(member);
        source.setPushState("1");
        List<Source> list = sourceService.findList(source);
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        for (Source source1 : list) {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("id", StringUtils.isBlank(source1.getId()) ? "" : source1.getId());
            map.put("pfPrice", StringUtils.isBlank(source1.getPfPrice()) ? "" : source1.getPfPrice());
            map.put("lsPrice", StringUtils.isBlank(source1.getLsPrice()) ? "" : source1.getLsPrice());
            map.put("mileage", StringUtils.isBlank(source1.getMileage()) ? "" : source1.getMileage());
            map.put("colour", StringUtils.isBlank(source1.getColour()) ? "" : source1.getColour());
            map.put("icon", StringUtils.isBlank(source1.getIcon()) ? "" : getRealPath(source1.getIcon()));
            map.put("brand", StringUtils.isBlank(source1.getBrand()) ? "" : source1.getBrand());
            map.put("motorcycleType", StringUtils.isBlank(source1.getMotorclcleType()) ? "" : source1.getMotorclcleType());
            map.put("carStyle", StringUtils.isBlank(source1.getCarStyle()) ? "" : source1.getCarStyle());
            map.put("registrationDate", StringUtils.isBlank(source1.getRegistrationDate()) ? "" : source1.getRegistrationDate());
            mapList.add(map);
        }
        ajaxJson.put("data", mapList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 删除车源草稿
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/deleteSourceDraft")
    public AjaxJson deleteSourceDraft(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        Source source = new Source();
        source.setU(member);
        List<Source> list = sourceService.findList(source);
        sourceService.deleteAll(list);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("操作成功");
        return ajaxJson;
    }

    /**
     * 删除求购草稿
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/deletePurchaseDraft")
    public AjaxJson deletePurchaseDraft(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        Purchase purchase = new Purchase();
        List<Purchase> list = purchaseService.findList(purchase);
        purchaseService.deleteAll(list);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("操作成功");
        return ajaxJson;
    }

    /**
     * 试用信息
     *
     * @return 数据
     */
    @RequestMapping("/tryInfo")
    public AjaxJson tryInfo() {
        AjaxJson ajaxJson = new AjaxJson();
        Free free = freeService.get("1");
        Map<String, Object> map = new ConcurrentHashMap<>();
        map.put("title", free.getTitle());
        map.put("intro", free.getIntro());
        map.put("days", free.getDays());
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 试用领取
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/takeTest")
    public AjaxJson takeTest(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        // 判断用户是否领取试用
        if (member.getTakeState().equals("1")) {
            ajaxJson.setMsg("已领取");
            return ajaxJson;
        }
        Free free = freeService.get("1");
        member.setTakeState("1");
        member.setStartDate(new Date());
        member.setEndDate(addDate(free.getDays()));
        memberService.save(member);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("领取成功");
        return ajaxJson;
    }

    /**
     * 展厅商家申请
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/exhibitionHallApply")
    public AjaxJson exhibitionHallApply(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String companyName = req.getString("companyName");
        String exhibitionHallId = req.getString("exhibitionHallId");
        String charter = req.getString("charter");
        String doorImg = req.getString("doorImg");
        String standImg = req.getString("standImg");
        String mobile = req.getString("mobile");
        String wechat = req.getString("wechat");
        String idImg = req.getString("idImg");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        // 判断是否是展厅商家
        if (!member.getVipType().equals("2")) {
            ajaxJson.setMsg("已申请通过");
            return ajaxJson;
        }
        ExhibitionHallMerchant exhibitionHallMerchant = new ExhibitionHallMerchant();
        exhibitionHallMerchant.setU(member);
        exhibitionHallMerchant.setAuditState("2");
        exhibitionHallMerchant.setCompanyName(companyName);
        exhibitionHallMerchant.setExhibitionHall(new ExhibitionHall(exhibitionHallId));
        exhibitionHallMerchant.setCharter(charter);
        exhibitionHallMerchant.setDoorImg(doorImg);
        exhibitionHallMerchant.setStandImg(standImg);
        exhibitionHallMerchant.setMobile(mobile);
        exhibitionHallMerchant.setWechat(wechat);
        exhibitionHallMerchant.setIdImg(idImg);
        exhibitionHallMerchantService.save(exhibitionHallMerchant);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("提交成功");
        return ajaxJson;
    }

    /**
     * 市场列表
     *
     * @return 数据
     */
    @RequestMapping("/marketList")
    public AjaxJson marketList() {
        AjaxJson ajaxJson = new AjaxJson();
        List<Market> list = marketService.findList(new Market());
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        for (Market market : list) {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("id", market.getId());
            map.put("title", market.getTitle());
            mapList.add(map);
        }
        ajaxJson.put("data", mapList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 展厅列表
     *
     * @return 数据
     */
    @RequestMapping("/exhibitionHallList")
    public AjaxJson exhibitionHallList() {
        AjaxJson ajaxJson = new AjaxJson();
        List<ExhibitionHall> list = exhibitionHallService.findList(new ExhibitionHall());
        List<Map<String, Object>> mapList = new CopyOnWriteArrayList<>();
        for (ExhibitionHall exhibitionHall : list) {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("id", exhibitionHall.getId());
            map.put("title", exhibitionHall.getTitle());
            mapList.add(map);
        }
        ajaxJson.put("data", mapList);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 市场商家申请
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/marketApply")
    public AjaxJson marketApply(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String motorsName = req.getString("motorsName");
        String marketId = req.getString("marketId");
        String charter = req.getString("charter");
        String doorImg = req.getString("doorImg");
        String standImg = req.getString("standImg");
        String mobile = req.getString("mobile");
        String wechat = req.getString("wechat");
        String idImg = req.getString("idImg");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        MarketMerchant marketMerchant = new MarketMerchant();
        marketMerchant.setU(member);
        marketMerchant.setMarket(new Market(marketId));
        marketMerchant.setMotorsName(motorsName);
        marketMerchant.setCharter(charter);
        marketMerchant.setDoorImg(doorImg);
        marketMerchant.setStandImg(standImg);
        marketMerchant.setMobile(mobile);
        marketMerchant.setWechat(wechat);
        marketMerchant.setIdImg(idImg);
        marketMerchant.setAuditState("2");
        marketMerchantService.save(marketMerchant);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 中介申请
     *
     * @return 数据
     */
    // @TokenValidate
    @RequestMapping("/agentApply")
    public AjaxJson agentApply(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String companyName = req.getString("companyName");
        String address = req.getString("address");
        String charter = req.getString("charter");
        String doorImg = req.getString("doorImg");
        String officeImg = req.getString("officeImg");
        String mobile = req.getString("mobile");
        String wechat = req.getString("wechat");
        String idImg = req.getString("idImg");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        Agent agent = new Agent();
        agent.setU(member);
        agent.setCompanyName(companyName);
        agent.setAddress(address);
        agent.setCharter(charter);
        agent.setDoorImg(doorImg);
        agent.setOfficeImg(officeImg);
        agent.setMobile(mobile);
        agent.setWechat(wechat);
        agent.setIdImg(idImg);
        agent.setAuditState("2");
        agentService.save(agent);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * 获取签名等相关的数据
     *
     * @return 数据
     */
    @RequestMapping("/getSign")
    public AjaxJson getSign(@RequestBody ReqJson req) throws Exception {
        AjaxJson ajaxJson = new AjaxJson();
        // 获取票据的url
        String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi";
        String accessToken = refreshToken();
        String requestUrl = GetPageAccessTokenUrl.replace("ACCESS_TOKEN", accessToken);
        HttpClient client = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(requestUrl);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(httpget, responseHandler);
        JSONObject OpenidJSONO = JSONObject.fromObject(response);

        // 用时间戳、随机数、jsapi_ticket和要访问的url按照签名算法拼接字符串
        String noncestr = UUID.randomUUID().toString();//随机字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳
        //4获取url
        String url = req.getString("path");
        //5、将参数排序并拼接字符串
        String ticket = String.valueOf(OpenidJSONO.get("ticket"));
        String str = "jsapi_ticket=" + ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;
        //6、将字符串进行sha1加密
        String signature = SHA1.SHA1(str);
        Map<String, String> map = new HashMap();
        map.put("timestamp", timestamp);
        map.put("noncestr", noncestr);
        map.put("signature", signature);
        map.put("appId", mpAppId);
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }


    /**
     * 刷新token
     */
    private String refreshToken() {
        String url = "grant_type=client_credential&appid=" + mpAppId + "&secret=" + mpAppSecret;
        String loginRet = HttpUtils.sendGet(wxAccToken, url);
        JSONObject json = JsonUtils.toBean(loginRet, JSONObject.class);
        String access_token = json.get("access_token").toString();
        return access_token;
    }

    /**
     * @return 求购列表
     */
    @RequestMapping("/purchaseList")
    public AjaxJson purchaseList(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String idlist = req.getString("idlist");
        String uid = req.getString("uid");
        String brand = req.getString("brand");
        Integer priceSort = req.getInteger("priceSort");
        String userType = req.getString("userType");
        Integer defalutSort = req.getInteger("defalutSort");
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        Purchase purchase = new Purchase();
        Page<Purchase> page = new Page<>();
        if (StringUtils.isNotBlank(idlist)) {
            String[] split = idlist.split(",");
            purchase.setDataScope(" AND a.id in ('" + idlist + "')");
            page.setPageNo(1);
            page.setPageSize(split.length);
        } else {
            if (Objects.isNull(pageNo) || Objects.isNull(pageNo)) {
                ajaxJson.setMsg("分页参数不能为空");
                return ajaxJson;
            }
            purchase.setPushState("2");
            page.setOrderBy(" a.create_date desc");
            if (Objects.equals(defalutSort, 2)) {
                page.setOrderBy(" a.create_date ASC");
            }
            if (Objects.nonNull(priceSort)) {
                if (Objects.equals(priceSort, 1)) {
                    page.setOrderBy(" a.car_budget desc");
                } else {
                    page.setOrderBy(" a.car_budget asc");
                }
            }
            if (StringUtils.isNotBlank(userType)) {
                if (Arrays.asList("1", "5").contains(userType)) {
                    purchase.setUserType(userType);
                } else if (userType.equals("2")) {
                    purchase.setDataScope(" and a.user_type in ('2','3','4')");
                }
            }
            if (StringUtils.isNotBlank(brand)) {
                purchase.setBrand(brand);
            }
            page.setPageNo(pageNo);
            page.setPageSize(pageSize);
        }
        Page<Purchase> list = purchaseService.findPage(page, purchase);
        //查询我的收藏
        PurchaseCollect purchaseCollect = new PurchaseCollect();
        purchaseCollect.setU(new Member(uid));
        List<String> collectList = purchaseCollectService.findList(purchaseCollect).stream().map(PurchaseCollect::getPurchase).map(Purchase::getId).collect(Collectors.toList());
        List<Map<String, Object>> collect = list.getList().stream().map(o -> {
            Map<String, Object> map = new ConcurrentHashMap<>();
            map.put("isCollect", CollUtil.isNotEmpty(collectList) && collectList.contains(o.getId()) ? 1 : 0);
            map.put("callName", StringUtils.isBlank(o.getCallName()) ? "" : o.getCallName());
            map.put("brand", StringUtils.isBlank(o.getBrand()) ? "" : o.getBrand());
            map.put("carStyle", StringUtils.isBlank(o.getCarStyle()) ? "" : o.getCarStyle());
            map.put("motorcycleType", StringUtils.isBlank(o.getMotorcycleType()) ? "" : o.getMotorcycleType());
            map.put("colour", StringUtils.isBlank(o.getColour()) ? "" : o.getColour());
            map.put("shift_type", StringUtils.isBlank(o.getShiftType()) ? "" : o.getShiftType());
            map.put("registeredDate", StringUtils.isBlank(o.getRegisteredDate()) ? "" : o.getRegisteredDate());
            map.put("mileage", StringUtils.isBlank(o.getMileage()) ? "" : o.getMileage());
            map.put("age", StringUtils.isBlank(o.getAge()) ? "" : o.getAge());
            map.put("carBudget", StringUtils.isBlank(o.getCarBudget()) ? "" : o.getCarBudget());
            map.put("mobile", StringUtils.isBlank(o.getMobile()) ? "" : o.getMobile());
            map.put("uid", StringUtils.isBlank(o.getU().getId()) ? "" : o.getU().getId());
            map.put("id", StringUtils.isBlank(o.getId()) ? "" : o.getId());
            return map;
        }).collect(Collectors.toList());
        Map<String, Object> data = new ConcurrentHashMap<>();
        ajaxJson.put("total", page.getLast());
        ajaxJson.put("count", page.getCount());
        ajaxJson.put("data", collect);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * @return 求购详情
     */
    @RequestMapping("/purchaseaInfo")
    public AjaxJson purchaseaInfo(PurchaseModel purchaseModel) {
        AjaxJson ajaxJson = new AjaxJson();
        if (StringUtils.isBlank(purchaseModel.getUid())) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(purchaseModel.getUid());
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (StringUtils.isBlank(purchaseModel.getId())) {
            ajaxJson.setMsg("求购id不能为空");
            return ajaxJson;
        }
        Purchase purchase = purchaseService.get(purchaseModel.getId());
        if (Objects.isNull(purchase)) {
            ajaxJson.setMsg("该求购信息不存在");
            return ajaxJson;
        }
        // 判断用户是否收藏该求购信息
        PurchaseCollect purchaseCollect = new PurchaseCollect();
        purchaseCollect.setU(member);
        purchaseCollect.setPurchase(purchase);
        List<PurchaseCollect> list = purchaseCollectService.findList(purchaseCollect);
        Map<String, Object> map = new HashMap<>();
        map.put("id", purchase.getId());
        map.put("isCollect", CollectionUtil.isEmpty(list) ? "0" : "1");
        map.put("callName", StringUtils.isBlank(purchase.getCallName()) ? "" : purchase.getCallName());
        map.put("brand", StringUtils.isBlank(purchase.getBrand()) ? "" : purchase.getBrand());
        map.put("carStyle", StringUtils.isBlank(purchase.getCarStyle()) ? "" : purchase.getCarStyle());
        map.put("colour", StringUtils.isBlank(purchase.getColour()) ? "" : purchase.getColour());
        map.put("shiftType", StringUtils.isBlank(purchase.getShiftType()) ? "" : purchase.getShiftType());
        map.put("registeredDate", StringUtils.isBlank(purchase.getRegisteredDate()) ? "" : purchase.getRegisteredDate());
        map.put("mileage", StringUtils.isBlank(purchase.getMileage()) ? "" : purchase.getMileage());
        map.put("age", StringUtils.isBlank(purchase.getAge()) ? "" : purchase.getAge());
        map.put("carBudget", StringUtils.isBlank(purchase.getCarBudget()) ? "" : purchase.getCarBudget());
        map.put("mobile", StringUtils.isBlank(purchase.getMobile()) ? "" : purchase.getMobile());
        ajaxJson.put("data", map);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * @return 我发布的车源
     */
    @RequestMapping("/mySource")
    public AjaxJson mySource(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (Objects.isNull(pageNo) || Objects.isNull(pageSize)) {
            ajaxJson.setMsg("分页参数不能为空");
            return ajaxJson;
        }
        Source source = new Source();
        source.setU(member);
        source.setPushState("2");
        Page<Source> page = sourceService.findPage(new Page<>(pageNo, pageSize), source);
        List<Map<String, Object>> collect = page.getList().stream().map(source1 -> {
            Map<String, Object> map = new HashMap<>();
            map.put("id", StringUtils.isBlank(source1.getId()) ? "" : source1.getId());
            map.put("icon", StringUtils.isBlank(source1.getIcon()) ? "" : getRealPath(source1.getIcon()));
            map.put("brand", StringUtils.isBlank(source1.getBrand()) ? "" : source1.getBrand());
            map.put("colour", StringUtils.isBlank(source1.getColour()) ? "" : source1.getColour());
            map.put("motorclcleType", StringUtils.isBlank(source1.getMotorclcleType()) ? "" : source1.getMotorclcleType());
            map.put("carStyle", StringUtils.isBlank(source1.getCarStyle()) ? "" : source1.getCarStyle());
            map.put("registrationDate", StringUtils.isBlank(source1.getRegistrationDate()) ? "" : source1.getRegistrationDate());
            map.put("mileage", StringUtils.isBlank(source1.getMileage()) ? "" : source1.getMileage());
            map.put("pfPrice", StringUtils.isBlank(source1.getPfPrice()) ? "" : source1.getPfPrice());
            map.put("lsPrice", StringUtils.isBlank(source1.getLsPrice()) ? "" : source1.getLsPrice());
            return map;
        }).collect(Collectors.toList());
        ajaxJson.put("total", page.getLast());
        ajaxJson.put("count", page.getCount());
        ajaxJson.put("data", collect);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * @return 我发布的求购
     */
    @RequestMapping("/myPurchase")
    public AjaxJson myPurchase(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (Objects.isNull(pageNo) || Objects.isNull(pageSize)) {
            ajaxJson.setMsg("分页参数不能为空");
            return ajaxJson;
        }
        Purchase purchase = new Purchase();
        purchase.setU(member);
        purchase.setPushState("2");
        Page<Purchase> page = purchaseService.findPage(new Page<>(pageNo, pageSize), purchase);
        List<Map<String, Object>> collect = page.getList().stream().map(o -> {
            Map<String, Object> map = new HashMap<>();
            map.put("callName", StringUtils.isBlank(o.getCallName()) ? "" : o.getCallName());
            map.put("brand", StringUtils.isBlank(o.getBrand()) ? "" : o.getBrand());
            map.put("carStyle", StringUtils.isBlank(o.getCarStyle()) ? "" : o.getCarStyle());
            map.put("motorcycleType", StringUtils.isBlank(o.getMotorcycleType()) ? "" : o.getMotorcycleType());
            map.put("colour", StringUtils.isBlank(o.getColour()) ? "" : o.getColour());
            map.put("shift_type", StringUtils.isBlank(o.getShiftType()) ? "" : o.getShiftType());
            map.put("registeredDate", StringUtils.isBlank(o.getRegisteredDate()) ? "" : o.getRegisteredDate());
            map.put("mileage", StringUtils.isBlank(o.getMileage()) ? "" : o.getMileage());
            map.put("age", StringUtils.isBlank(o.getAge()) ? "" : o.getAge());
            map.put("carBudget", StringUtils.isBlank(o.getCarBudget()) ? "" : o.getCarBudget());
            map.put("mobile", StringUtils.isBlank(o.getMobile()) ? "" : o.getMobile());
            map.put("uid", StringUtils.isBlank(o.getU().getId()) ? "" : o.getU().getId());
            map.put("id", StringUtils.isBlank(o.getId()) ? "" : o.getId());
            return map;
        }).collect(Collectors.toList());
        ajaxJson.put("total", page.getLast());
        ajaxJson.put("count", page.getCount());
        ajaxJson.put("data", collect);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * @return 数据
     */
    @RequestMapping("/getImage")
    public AjaxJson getImage(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String type = req.getString("type");
        Image image = new Image();
        image.setImageType(type);
        List<Image> list = imageService.findList(image);
        ajaxJson.put("path", getRealPath(list.get(0).getPath()));
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }

    /**
     * @return 修改用户信息
     */
    @RequestMapping("/editUserInfo")
    public AjaxJson editUserInfo(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        String nickname = req.getString("nickname");
        String photo = req.getString("photo");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        member.setNickname(nickname);
        member.setPhoto(photo);
        memberService.save(member);
        ajaxJson.setCode(0);
        ajaxJson.setMsg("操作成功");
        return ajaxJson;
    }

    /**
     * @return 数据
     */
    @RequestMapping("/test")
    public AjaxJson test(@RequestBody ReqJson req) {
        AjaxJson ajaxJson = new AjaxJson();
        String uid = req.getString("uid");
        Integer pageNo = req.getInteger("pageNo");
        Integer pageSize = req.getInteger("pageSize");
        if (StringUtils.isBlank(uid)) {
            ajaxJson.setMsg("用户id不能为空");
            return ajaxJson;
        }
        Member member = memberService.get(uid);
        if (Objects.isNull(member)) {
            ajaxJson.setMsg("该用户不存在");
            return ajaxJson;
        }
        if (Objects.isNull(pageNo) || Objects.isNull(pageSize)) {
            ajaxJson.setMsg("分页参数不能为空");
            return ajaxJson;
        }
        ajaxJson.setCode(0);
        ajaxJson.setMsg("请求成功");
        return ajaxJson;
    }
}